package core.utils
{
	import flash.display.Sprite;
	import flash.events.ContextMenuEvent;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	
	import core.formats.SharedItem;
	/**
	 * 本地缓存管理器，包含了3个方法:
	 * <li>申请本地缓存空间 initLocalCache(size:int):void</li>
	 * <li>缓存到本地 saveToLocal(si:SharedItem):void</li>
	 * <li>从缓存取得数据getDataFromCache(id:String):SharedItem</li><br/>
	 * 清空缓存是通过根目录的右键菜单实现的
	 * @author Ado
	 * @see #core.formats.SharedItem
	 * 
	 * @example
	 * <listing>
	 * //申请本地缓存
	 * var someSprite:Sprite = new Sprite();
	 * LocalCacheManager.initLocalCache(someSprite,100000);
	 * 
	 * //存放数据到本地缓存
	 * var si:SharedItem = new ShareItem();
	 * si.version = 1.2;
	 * si.key = "something";
	 * si.data = 1;
	 * LocalCacheManager.saveToLocal9si);
	 * 
	 * //从缓存取数据
	 * var si:SharedItem = getDataFromCache("something");
	 * trace(si.data); // 1
	 * 
	 * </listing>
	 */
	public class LocalCache
	{
		public function LocalCache()
		{
			throw new Error("Can not be instantiated...");
		}
		private static var sharedObj:SharedObject;
		/**
		 * 初始化本地存储对象，申请本地存储空间
		 * @param size 需要申请的空间容量，单位：Byte, 默认10M
		 */		
		public static function initLocalCache(root:Sprite, size:int=10485760):void
		{
			sharedObj = SharedObject.getLocal("GameCache");
			var status:String = sharedObj.flush(size);
			if(status == SharedObjectFlushStatus.FLUSHED)
			{
				trace("Cache申请成功...");
			}else if(status == SharedObjectFlushStatus.PENDING)
			{
				trace("Cache申请失败...");
				return;
			}
			//申请完成之后向舞台添加右键事件清理缓存
			var item:ContextMenuItem = new ContextMenuItem("清除缓存数据");
			var menu:ContextMenu = new ContextMenu();
			menu.customItems.push(item);
			item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, clearCache);
			root.contextMenu = menu;
		}
		/**
		 *  清理缓存数据，由鼠标右键菜单的对应条目触发
		 * @param e
		 * 
		 */		
		private static function clearCache(e:ContextMenuEvent):void
		{
			sharedObj.clear();
			for(var key:String in sharedObj.data)
			{
				delete sharedObj.data[key];
			}
		}
		/**
		 * 存入数据到本地缓存当中 
		 * @param si
		 * 
		 */		
		public static function saveToLocal(si:SharedItem):void
		{
			if(sharedObj.data.hasOwnProperty(si.key))
			{
				var temp:SharedItem = new SharedItem(sharedObj.data[si.key]);
				if(si.version < temp.version)
				{
					return;
				}
			}
			sharedObj.data[si.key]=si;
		}
		/**
		 * 从cache中取得缓存本地的数据 
		 * @param key
		 * @return 
		 * 
		 */		
		public static function getDataFromCache(key:String):SharedItem
		{
			if(sharedObj.data.hasOwnProperty(key))
			{
				return sharedObj.data[key] as SharedItem;
			}
			return null;
		}
	}
}